<?php

namespace App\Admin\Models;

use App\Admin\Models\SystemModel;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;

class WorshipBibleVolume extends Model
{
    use SoftDeletes;

    protected $guarded = []; 

    public function __construct(){
        parent::__construct();
        $this->mergeCasts(SystemModel::fieldCasts($this->getTable()));
    }

    /**
     * 获取经文列表
     * @param array $params 参数
     * @return array $bvs
     */
    public function lists($params)
    {

        $bc = new WorshipBibleChapter();
        if (isset($params['scope']) && $params['scope']) {
            $params['scope'] = str_replace('-', ',', $params['scope']);
            $pv = $bc->parse($params['scope']);
            $bvs = $this->whereIn($pv['bv'][0],$pv['bv'][1])
                ->get()
                ->toArray();
            foreach ($bvs as $key => $value) {   
                $bvs[$key]['bc'] = $bc->withTrashed()
                    ->where('volume_id',$value['id'])
                    ->whereIn($pv['bc'][0],$pv['bc'][1])
                    ->get(['chapter_id','verse_id','lection'])
                    ->toArray();
            }
        } elseif (isset($params['keywords']) && $params['keywords']) {
            $params['keywords'] = trim($params['keywords']);
            $bcs = $bc->where('lection','like',"%{$params['keywords']}%")
                ->get(['volume_id','chapter_id','verse_id','lection'])
                ->toArray();
            $ids = empty($bcs) ? (0) : array_column($bcs, 'volume_id');
            $bvs = $this->whereIn('id',$ids)
                ->get()
                ->toArray();
            foreach ($bvs as $key => $value) {
                $bvs[$key]['bc'] = [];
                foreach ($bcs as $k => $v) {
                    if ($value['id'] == $v['volume_id']) {
                        $bvs[$key]['bc'][] = $v;
                    }
                }
            }
        }
        return $bvs;
    }

    /**
     * 获取章节列表
     * @param array $scope 范围
     * @return array $bcs
     */
    public function lections($scope)
    {
        $bcs = [];
        $bc = new WorshipBibleChapter();
        if ($scope) {
            $scope = str_replace('-', ',', $scope);
            $pv = $bc->parse($scope);
            $volumeIds = $this->whereIn($pv['bv'][0],$pv['bv'][1])
                ->pluck('id')
                ->toArray();
            $pv['bc'][0] = 'bc.id';
            $bcs = $bc->from('worship_bible_chapters as bc')
                ->withTrashed()
                ->join('worship_bible_volumes as bv','bv.id','=','bc.volume_id')
                ->whereIn('volume_id',$volumeIds)
                ->whereIn($pv['bc'][0],$pv['bc'][1])
                ->get([
                    DB::raw(
                        "concat( IFNULL( bv.short_name, '' ), 
                        IFNULL( bc.chapter_id, '' ), 
                        ':', 
                        IFNULL( bc.verse_id, '' ) ) AS vcv"
                    ),
                    'bc.lection'
                ])
                ->toArray();
        }
        return $bcs;
    }

    /**
     * 解析简称
     * @param string $scope
     * @return array $ShortNames
     */
    function parseShortName($scope){
        $columnShortName = $this->pluck('short_name')->toArray();
        // 简称的范围
        $shortNames = [];
        // 冒号位置
        $colonLocates = getCharpos($scope,':');
        if ($colonLocates) {
            // 分号位置
            $semicolonLocates = getCharpos($scope,';');
            // 分号位置从0开始
            array_unshift($semicolonLocates, 0);
            // 分号位置数量
            $countSemicolonLocates = count($semicolonLocates);
            // echo $countSemicolonLocates;exit;
            // 范围的字符串总长度
            $scopeLength = mb_strlen($scope);
            foreach ($colonLocates as $key => $value) {
                $shortName = mb_substr($scope,$value-1,1);
                if (!in_array($shortName, $columnShortName)) {
                    $shortName = mb_substr($scope,$value-2,2);
                }
                for ($i=0; $i < $countSemicolonLocates; $i++) { 
                    $locate1 = $semicolonLocates[$i];
                    $locate2 = isset($semicolonLocates[$i+1]) ? $semicolonLocates[$i+1] : $scopeLength;
                    $locates = [$locate1,$locate2];
                    sort($locates);
                    if ($value >= $locates[0] && $value <= $locates[1]) {
                        $shortNames[$i][] = $shortName;
                    }
                }
            }
            foreach ($shortNames as $key => $value) {
                foreach ($value as $k => $v) {
                    if (!in_array($v, $columnShortName)) {
                        unset($shortNames[$key][$k]);
                    }
                }
            }
            $shortNames = array_filter($shortNames);
        } else {
            foreach (explode(';', $scope) as $key => $value) {
                foreach (explode(',', $value) as $k => $v) {
                    if (in_array($v, $columnShortName)) {
                        $shortNames[$key][$k] = $v;
                    }
                }
            }
        }
        return array_values($shortNames);
    }
    
    /**
     * 根据卷范围获取起止id
     * @param mixed $shortNames
     * @param array $ids
     */
    public function _ids($shortNames)
    {
        $ids = fill_number(
            $this->whereIn('short_name',$shortNames)
            ->orderBy('id')
            ->pluck('id')
            ->toArray()
        );
        return $ids;
    }
}
